package com.qys.livesMall.app.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.app.user.mapper.H2AppUserRechargeWithdrawalsMapper;
import com.qys.livesMall.app.user.model.dto.app.AppUserApplyWithdrawalDTO;
import com.qys.livesMall.app.user.model.dto.app.AppUserInfoTeamIncomeDTO;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.model.entity.UserRewardConfig;
import com.qys.livesMall.app.user.model.entity.UserShopStatistics;
import com.qys.livesMall.app.user.model.entity.UserStatisticsTeam;
import com.qys.livesMall.app.user.mapper.UserStatisticsTeamMapper;
import com.qys.livesMall.app.user.model.vo.app.AppUserInfoTeamDetailVo;
import com.qys.livesMall.app.user.model.vo.app.AppUserInfoTeamVo;
import com.qys.livesMall.app.user.model.vo.sys.SysUserStatisticsTeamVO;
import com.qys.livesMall.app.user.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.enums.FinanceMessageEnum;
import com.qys.livesMall.finance.mapper.FinanceUserAccountDetailMapper;
import com.qys.livesMall.finance.mapper.FinanceUserAccountMapper;
import com.qys.livesMall.finance.model.dto.user.UserInfoTeamIncomeDTO;
import com.qys.livesMall.finance.model.entity.user.FinanceUserAccount;
import com.qys.livesMall.finance.model.vo.AppUserInfoTeamIncomeVO;
import com.qys.livesMall.finance.service.FinanceUserAccountService;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.framework.view.BaseQuery;
import com.qys.livesMall.framework.view.QysPage;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 团队统计数据 服务实现类
 * </p>
 *
 * @author
 * @since 2023-08-02
 */
@Service
public class UserStatisticsTeamServiceImpl extends ServiceImpl<UserStatisticsTeamMapper, UserStatisticsTeam> implements UserStatisticsTeamService {

    @Resource
    private UserShopStatisticsService userShopStatisticsService;
    @Resource
    private IH2AppUserService ih2AppUserService;
    @Resource
    private UserStatisticsInfoService userStatisticsInfoService;
    @Resource
    private H2AppUserRechargeWithdrawalsMapper rechargeWithdrawalsMapper;
    @Resource
    private FinanceUserAccountDetailMapper financeUserAccountDetailMapper;
    @Resource
    private AppUserRelationService relationService;
    @Resource
    private MessageServer messageServer;
    @Resource
    private FinanceUserAccountMapper financeUserAccountMapper;
    @Resource
    private UserRewardConfigService userRewardConfigService;

    @Override
    public Boolean editWaitWithdrawal(AppUserApplyWithdrawalDTO appUserApplyWithdrawalDTO) {
        UserShopStatistics userShopStatistics=userShopStatisticsService.selectByUserId(Long.valueOf(appUserApplyWithdrawalDTO.getUserId()));
        if (null==userShopStatistics){
            return false;
        }
        List<UserStatisticsTeam> userStatisticsTeams =getByTeamId(userShopStatistics.getTeamId());
        if (CollectionUtils.isEmpty(userStatisticsTeams)){
            return false;
        }
        UserStatisticsTeam userStatisticsTeam = userStatisticsTeams.get(0);
        if (appUserApplyWithdrawalDTO.getType()==1){
            userStatisticsTeam.setWaitWithdrawal(userStatisticsTeam.getWaitWithdrawal().add(appUserApplyWithdrawalDTO.getAmount()));
        }else {
            userStatisticsTeam.setWaitWithdrawal(userStatisticsTeam.getWaitWithdrawal().subtract(appUserApplyWithdrawalDTO.getAmount()));
        }
        return updateById(userStatisticsTeam);
    }

    @Override
    public UserStatisticsTeam getbyUserid(Integer type, Long userId) {
        return baseMapper.getbyUserid(type,userId);
    }

    @Override
    public List<UserStatisticsTeam> getByTeamId(Long teamId) {
        LambdaQueryWrapper<UserStatisticsTeam> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserStatisticsTeam::getTeamId,teamId);
        List<UserStatisticsTeam> list= baseMapper.selectList(queryWrapper);
        for (UserStatisticsTeam bean: list){
            bean.setTeamBalance(null==bean.getTeamBalance()?BigDecimal.ZERO:bean.getTeamBalance());
            bean.setTeamDifference(null==bean.getTeamDifference()?BigDecimal.ZERO:bean.getTeamDifference());
            bean.setTeamWithdrawal(null==bean.getTeamWithdrawal()?BigDecimal.ZERO:bean.getTeamWithdrawal());
            bean.setWaitWithdrawal(null==bean.getWaitWithdrawal()?BigDecimal.ZERO:bean.getWaitWithdrawal());
            bean.setCumulative(null==bean.getCumulative()?BigDecimal.ZERO:bean.getCumulative());
        }
        return list;
    }

   /* @Override
    public AppUserInfoTeamVo getUserTeam(Long userId) {
        H2AppUser h2AppUser=ih2AppUserService.getById(userId);
        AppUserInfoTeamVo appUserInfoTeamVo=new AppUserInfoTeamVo();
        appUserInfoTeamVo.setId(h2AppUser.getId());
        appUserInfoTeamVo.setAvatarUrl(h2AppUser.getAvatar());
        appUserInfoTeamVo.setName(h2AppUser.getNickName());
        appUserInfoTeamVo.setRandomId(h2AppUser.getUserRandomId());
*//*      //总佣金
        UserStatisticsInfo userStatisticsInfo = userStatisticsInfoService.selectByUserId(userId);
        if (null != userStatisticsInfo){
            appUserInfoTeamVo.setCumulative(userStatisticsInfo.getCumulative()==null?BigDecimal.ZERO:userStatisticsInfo.getCumulative());
        }

        //本周
        BigDecimal weekendCumulative=userShopStatisticsDayLogService.getWeekbyUserid(userId,0);
        appUserInfoTeamVo.setWeekendCumulative(weekendCumulative==null?BigDecimal.ZERO:weekendCumulative);
        //当天
        BigDecimal dayCumulative=userShopStatisticsDayLogService.getDaybyUserid(userId,0);
        appUserInfoTeamVo.setDayCumulative(dayCumulative==null?BigDecimal.ZERO:dayCumulative);*//*

        //当前用户的下级
        List<String> ids=ih2AppUserService.gettreeList(userId.toString(),null);
        if (CollectionUtils.isEmpty(ids)){
            ids=new ArrayList<>();
        }
        ids.add(userId.toString());
        List<String> codes = AccountBusinessTypeEnum.getUserCommissionCode();
        //总佣金
        BigDecimal sumCumulative= financeUserAccountDetailMapper.getCumulativeIncome(userId,codes,null);
        appUserInfoTeamVo.setCumulative(sumCumulative==null?BigDecimal.ZERO:sumCumulative);
        //本周
        BigDecimal weekendCumulative=financeUserAccountDetailMapper.getCumulativeIncome(userId,codes,1);
        appUserInfoTeamVo.setWeekendCumulative(weekendCumulative==null?BigDecimal.ZERO:weekendCumulative);
        //当天
        BigDecimal dayCumulative=financeUserAccountDetailMapper.getCumulativeIncome(userId,codes,2);
        appUserInfoTeamVo.setDayCumulative(dayCumulative==null?BigDecimal.ZERO:dayCumulative);

        List<Long> rechargeList = rechargeWithdrawalsMapper.getChildInfo(Arrays.asList(userId));
        appUserInfoTeamVo.setDirectNum(rechargeList.size());
        appUserInfoTeamVo.setInviteNum(rechargeList.size());
        if (CollectionUtils.isEmpty(rechargeList)){
            return appUserInfoTeamVo;
        }
//            二代
        List<Long> childUserIds = ih2AppUserService.getChildUserIds(rechargeList);
        if (CollectionUtils.isEmpty(childUserIds)){
            return appUserInfoTeamVo;
        }
        List<String> twoids = childUserIds.stream().map(s -> s.toString()).collect(Collectors.toList());
        List<String> secondRechargeList = rechargeWithdrawalsMapper.getUserRechargeList(twoids);
        appUserInfoTeamVo.setSecondGrandNum(secondRechargeList.size());

//            三代
        List<Long> grandChildUserIds = ih2AppUserService.getChildUserIds(childUserIds);
        if (CollectionUtils.isNotEmpty(grandChildUserIds)){
            List<String> threeids = grandChildUserIds.stream().map(s -> s.toString()).collect(Collectors.toList());
            List<String> grandRechargeList = rechargeWithdrawalsMapper.getUserRechargeList(threeids);
            appUserInfoTeamVo.setThirdGrandNum(grandRechargeList.size());
        }
        appUserInfoTeamVo.setTeamNum(appUserInfoTeamVo.getDirectNum() + appUserInfoTeamVo.getSecondGrandNum() + appUserInfoTeamVo.getThirdGrandNum());
        return appUserInfoTeamVo;
    }

     @Override
    public Page<AppUserInfoTeamDetailVo> getUserlist(BaseQuery baseQuery) {
        Page<AppUserInfoTeamDetailVo> page = new Page<>(baseQuery.getPageNum(), baseQuery.getPageSize());
        List<Long> userIdsOne=new ArrayList<>();
        List<Long> userIdstwo=new ArrayList<>();
        List<Long> userIdsThree=new ArrayList<>();
        //查询直推
        List<Long> rechargeList = rechargeWithdrawalsMapper.getChildInfo(Arrays.asList(SecurityUtils.getUserId()));
        if (CollectionUtils.isNotEmpty(rechargeList)){
            userIdsOne.addAll(rechargeList);
        }

        //查询第二代
        List<Long> childUserIds =null;
        if (CollectionUtils.isNotEmpty(rechargeList)){
            childUserIds = ih2AppUserService.getChildUserIds(rechargeList);
            if (CollectionUtils.isNotEmpty(childUserIds)){
                List<String> twoids = childUserIds.stream().map(s -> s.toString()).toList();
                List<String> secondRechargeList = rechargeWithdrawalsMapper.getUserRechargeList(twoids);
                if (CollectionUtils.isNotEmpty(secondRechargeList)){
                    List<Long> secondRechargeListToLong = secondRechargeList.stream().map(s -> Long.valueOf(s)).toList();
                    userIdstwo.addAll(secondRechargeListToLong);
                }
            }
        }

        //查询第三代
        if (CollectionUtils.isNotEmpty(childUserIds)){
            List<Long> grandChildUserIds = ih2AppUserService.getChildUserIds(childUserIds);
            if (CollectionUtils.isNotEmpty(grandChildUserIds)){
                List<String> threeids = grandChildUserIds.stream().map(s -> s.toString()).collect(Collectors.toList());
                List<String> grandRechargeList = rechargeWithdrawalsMapper.getUserRechargeList(threeids);
                if (CollectionUtils.isNotEmpty(grandRechargeList)){
                    List<Long> grandRechargeListToLong = grandRechargeList.stream().map(s -> Long.valueOf(s)).toList();
                    userIdsThree.addAll(grandRechargeListToLong);
                }
            }
        }
        List<AppUserInfoTeamDetailVo> users=null;
        if (baseQuery.getId().equals("1")){
            if (CollectionUtils.isEmpty(userIdsOne)){
                return new Page<>();
            }
            users=ih2AppUserService.getbyUserids(page,userIdsOne);
        }
        if (baseQuery.getId().equals("2")){
            if (CollectionUtils.isEmpty(userIdstwo)){
                return new Page<>();
            }
            users=ih2AppUserService.getbyUserids(page,userIdstwo);
        }
        if (baseQuery.getId().equals("3")){
            if (CollectionUtils.isEmpty(userIdsThree)){
                return new Page<>();
            }
            users=ih2AppUserService.getbyUserids(page,userIdsThree);
        }
        page.setRecords(users);
        return page;
    }

    */

    @Override
    public AppUserInfoTeamVo getUserTeam(Long userId) {
        H2AppUser h2AppUser=ih2AppUserService.getById(userId);
        AppUserInfoTeamVo appUserInfoTeamVo=new AppUserInfoTeamVo();
        appUserInfoTeamVo.setId(h2AppUser.getId());
        appUserInfoTeamVo.setAvatarUrl(h2AppUser.getAvatar());
        appUserInfoTeamVo.setName(h2AppUser.getNickName());
        appUserInfoTeamVo.setRandomId(h2AppUser.getUserRandomId());
        appUserInfoTeamVo.setInviteNum(0);
        //当前用户的下级
        List<String> ids=ih2AppUserService.gettreeList(userId.toString(),null);
        if (CollectionUtils.isEmpty(ids)){
            ids=new ArrayList<>();
        }
        ids.add(userId.toString());
        List<String> codes = AccountBusinessTypeEnum.getUserCommissionCode();
        //总佣金
        BigDecimal sumCumulative= financeUserAccountDetailMapper.getCumulativeIncome(userId,codes,null);
        appUserInfoTeamVo.setCumulative(sumCumulative==null?BigDecimal.ZERO:sumCumulative);
        //本周
        BigDecimal weekendCumulative=financeUserAccountDetailMapper.getCumulativeIncome(userId,codes,1);
        appUserInfoTeamVo.setWeekendCumulative(weekendCumulative==null?BigDecimal.ZERO:weekendCumulative);
        //当天
        BigDecimal dayCumulative=financeUserAccountDetailMapper.getCumulativeIncome(userId,codes,2);
        appUserInfoTeamVo.setDayCumulative(dayCumulative==null?BigDecimal.ZERO:dayCumulative);

        List<Long> rechargeList =relationService.getUserLowerLevels(userId,1);
        appUserInfoTeamVo.setDirectNum(rechargeList.size());

//      二代
        List<Long> secondRechargeList = relationService.getUserLowerLevels(userId,2);
        appUserInfoTeamVo.setSecondGrandNum(secondRechargeList.size());
//      三代
        List<Long> grandRechargeList = relationService.getUserLowerLevels(userId,3);
        appUserInfoTeamVo.setThirdGrandNum(grandRechargeList.size());
        appUserInfoTeamVo.setTeamNum(appUserInfoTeamVo.getDirectNum() + appUserInfoTeamVo.getSecondGrandNum() + appUserInfoTeamVo.getThirdGrandNum());

        List<Long> userIds=new ArrayList<>();
        userIds.addAll(rechargeList);
        userIds.addAll(secondRechargeList);
        userIds.addAll(grandRechargeList);
        if (CollectionUtils.isNotEmpty(userIds)){
            LambdaQueryWrapper<UserRewardConfig> query=new LambdaQueryWrapper<>();
            query.eq(UserRewardConfig::getAwardType,10);
            query.last("limit 1");
            UserRewardConfig rewardConfigs=userRewardConfigService.getOne(query);
            if (null == rewardConfigs || null == rewardConfigs.getAwardUnit()){
                return appUserInfoTeamVo;
            }
            LambdaQueryWrapper<FinanceUserAccount> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.in(FinanceUserAccount::getUserId,userIds);
            queryWrapper.ge(FinanceUserAccount::getTotalBalance,rewardConfigs.getAwardUnit());
            Long count=financeUserAccountMapper.selectCount(queryWrapper);
            appUserInfoTeamVo.setInviteNum(count.intValue());
        }
        return appUserInfoTeamVo;
    }

    @Override
    public Page<AppUserInfoTeamDetailVo> getUserlist(BaseQuery baseQuery) {
        Page<AppUserInfoTeamDetailVo> page = new Page<>(baseQuery.getPageNum(), baseQuery.getPageSize());
        List<AppUserInfoTeamDetailVo> users=null;
        if (baseQuery.getId().equals("1")){
            List<Long> userIdsOne = relationService.getUserLowerLevels(SecurityUtils.getUserId(),1);
            if (CollectionUtils.isEmpty(userIdsOne)){
                return new Page<>();
            }
            users=ih2AppUserService.getbyUserids(page,userIdsOne);
        }
        if (baseQuery.getId().equals("2")){
            List<Long> userIdstwo = relationService.getUserLowerLevels(SecurityUtils.getUserId(),2);
            if (CollectionUtils.isEmpty(userIdstwo)){
                return new Page<>();
            }
            users=ih2AppUserService.getbyUserids(page,userIdstwo);
        }
        if (baseQuery.getId().equals("3")){
            List<Long> userIdsThree = relationService.getUserLowerLevels(SecurityUtils.getUserId(),3);
            if (CollectionUtils.isEmpty(userIdsThree)){
                return new Page<>();
            }
            users=ih2AppUserService.getbyUserids(page,userIdsThree);
        }
        page.setRecords(users);
        return page;
    }

    @Override
    public  Page<AppUserInfoTeamIncomeVO> getUserlistIncome(AppUserInfoTeamIncomeDTO incomeDTO) {
        //当前用户的下级
        String userid=SecurityUtils.getUserId().toString();
        List<String> codes = AccountBusinessTypeEnum.getUserCommissionCode();
        UserInfoTeamIncomeDTO userInfoTeamIncomeDTO=new UserInfoTeamIncomeDTO();
        BeanUtil.copyProperties(incomeDTO,userInfoTeamIncomeDTO);
        userInfoTeamIncomeDTO.setUserIds(Arrays.asList(userid));
        if (StringUtils.isNoneEmpty(incomeDTO.getCode())){
            userInfoTeamIncomeDTO.setCodeArr(Arrays.asList(incomeDTO.getCode()));
        }else {
            userInfoTeamIncomeDTO.setCodeArr(codes);
        }
        Page<AppUserInfoTeamIncomeVO> page = new Page<>(incomeDTO.getPageNum(), incomeDTO.getPageSize());
        page=financeUserAccountDetailMapper.getUserlistIncome(page,userInfoTeamIncomeDTO);
        page.getRecords().forEach(e -> {
            e.setDesc(messageServer.getMsg(FinanceMessageEnum.getEnum(e.getCode())));
            LocalDateTime payDate =e.getPayDate();
            if (null != payDate){
                e.setPayDateLongTime(payDate.toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
            }
        });
        return page;
    }

    @Override
    public QysPage<SysUserStatisticsTeamVO> teamPage(BaseQuery pageDTO) {
        LambdaQueryWrapper<UserStatisticsTeam> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(UserStatisticsTeam::getId);
        Page<UserStatisticsTeam> page=baseMapper.selectPage(new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize()), queryWrapper);
        List<SysUserStatisticsTeamVO> vos=new ArrayList<>();
        page.getRecords().forEach(e -> {
            SysUserStatisticsTeamVO sysUserStatisticsTeamVO=new SysUserStatisticsTeamVO();
            BeanUtil.copyProperties(e,sysUserStatisticsTeamVO);
           // sysUserStatisticsTeamVO.setThirtyDaysAdd(e.getRecentAdd()==null?0:e.getRecentAdd());
            sysUserStatisticsTeamVO.setTeamWithdrawalAuditing(e.getWaitWithdrawal()==null?BigDecimal.ZERO:e.getWaitWithdrawal());
            //查询昨日数据
            Integer yesterdayAdd=baseMapper.queryAddPeopleNum(e.getId(),1);
            sysUserStatisticsTeamVO.setYesterdayAdd(yesterdayAdd==null?0:yesterdayAdd);
            Integer sevenDaysAdd=baseMapper.queryAddPeopleNum(e.getId(),7);
            sysUserStatisticsTeamVO.setSevenDaysAdd(sevenDaysAdd==null?0:sevenDaysAdd);
            Integer thirtyDaysAdd=baseMapper.queryAddPeopleNum(e.getId(),30);
            sysUserStatisticsTeamVO.setThirtyDaysAdd(thirtyDaysAdd==null?0:thirtyDaysAdd);

            BigDecimal WithdrawalYesterday = baseMapper.getWithdrawalAmount(e.getId());
            sysUserStatisticsTeamVO.setWithdrawalYesterday(WithdrawalYesterday==null?BigDecimal.ZERO:WithdrawalYesterday);

            BigDecimal WithdrawalToday = baseMapper.getInitiateWithdrawalAmount(e.getId());
            sysUserStatisticsTeamVO.setWithdrawalToday(WithdrawalToday==null?BigDecimal.ZERO:WithdrawalToday);

            if (null == e.getName()){
                H2AppUser h2AppUser = ih2AppUserService.getById(e.getTeamId());
                sysUserStatisticsTeamVO.setName(null==h2AppUser?"":h2AppUser.getNickName());
            }
            vos.add(sysUserStatisticsTeamVO);
        });
        return  QysPage.build(pageDTO).setRecords(vos).setTotal(page.getTotal());
    }
}
